package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.framework.web.domain.server.SysFile;
import com.ruoyi.system.service.impl.OssServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.File;
import com.ruoyi.system.service.ISysFileService;
import oshi.software.os.OSService;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/system/file")
public class SysFileController extends BaseController {
    @Autowired
    private OssServiceImpl fileService;

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 查询文件列表
     */
    @GetMapping("/list")
    public TableDataInfo list(File file) {
        startPage();
        List<File> list = sysFileService.selectFileList(file);
        System.out.println(list);
        return getDataTable(list);
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @Log(title = "文件上传", businessType = BusinessType.INSERT)
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        try {
            File file01 = new File();
            file01.setName(file.getName());
            file01.setSize(file.getSize() + "");
            file01.setOriginalName(file.getOriginalFilename());
            file01.setType(file.getContentType());

            // 文件类型校验
            String extension = FileTypeUtils.getExtension(file.getOriginalFilename());
            if (isAllowedExtension(extension)) {
                return error("不支持的文件类型");
            }

            // 上传文件
            String sysFile = fileService.uploadFile(file);
            System.out.println(sysFile);
            file01.setUrl(sysFile);
            int i = sysFileService.insertFile(file01);
            System.out.println(i);
            return success(sysFile);
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 下载文件
     */
    @GetMapping("/download/{fileId}")
    public void download(@PathVariable("fileId") Long fileId, HttpServletResponse response) throws IOException {
        try {
            File sysFile = sysFileService.selectFileById(fileId);
            if (sysFile == null) {
                throw new RuntimeException("文件不存在");
            }

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(sysFile.getName(), "UTF-8"));

            sysFileService.downloadFile(fileId, response.getOutputStream());
        } catch (Exception e) {
            throw new RuntimeException("下载文件失败");
        }
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/{fileId}")
    @Log(title = "文件删除", businessType = BusinessType.DELETE)
    public AjaxResult delete(@PathVariable Long fileId) {
        return toAjax(sysFileService.deleteFile(fileId));
    }

    /**
     * 检查文件类型是否允许
     */
    private boolean isAllowedExtension(String extension) {
        String[] allowedExtensions = {".doc", ".docx", ".pdf", ".txt"};
        for (String allowed : allowedExtensions) {
            if (allowed.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }
}